package com.geyue.core.service.impl;

import com.geyue.common.base.service.impl.BaseServiceImpl;
import com.geyue.common.cache.Cache;
import com.geyue.common.toolbox.result.Res;
import com.geyue.common.util.SmsUtil;
import com.geyue.common.util.StrUtils;
import com.geyue.core.mapper.UserMapper;
import com.geyue.core.model.User;
import com.geyue.core.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by Lyon on 2017/3/27.
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Res reg(User user) {

        String mobile = user.getMobile();
        //取出内存中code
        String code = Cache.getSingleCode().get(mobile);

        if(StrUtils.isEmpty(code) || !code.equals(user.getMsgCode()))
            return Res.fail("验证码错误,请重新尝试!");

        if(userMapper.getByMobile(mobile) != null)
            return Res.fail("号码已经被注册过!");

        if(super.saveNotEmpty(user) > 0)
            return Res.success("注册成功!");

        return Res.fail("注册失败!");
    }

    @Override
    public Res msg(String mobile) {
        //验证上次发送时间
        boolean isOk = Cache.msg_send_validate(mobile);

        if(!isOk)
            return Res.fail("请稍候重试!");
        //发送
       String code = SmsUtil.send(mobile);

       if("-1".equals(code))
           return Res.fail("发送失败,请稍候重试!");
        //放入内存
        Cache.getSingleCode().put(mobile,code);

        return Res.success("发送成功!",code);
    }
}
